#include <jni.h>
#include <string>
#include "Rtmp.h"

#ifdef __cplusplus
extern "C" {
#endif
extern "C"
JNIEXPORT jlong JNICALL
Java_com_ivideo_avcore_rtmplive_RtmpUtils_init(JNIEnv *env, jclass clazz, jstring url_, jint w,
                                               jint h, jint time_out) {
    const char *url = env->GetStringUTFChars(url_, 0);
    Rtmp *rtmp = new Rtmp();
    rtmp->init(url, w, h, time_out);
    env->ReleaseStringUTFChars(url_, url);
    return reinterpret_cast<long> (rtmp);
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_ivideo_avcore_rtmplive_RtmpUtils_sendSpsAndPps(JNIEnv *env, jclass clazz, jlong cptr,
                                                        jbyteArray sps_, jint spsLen,
                                                        jbyteArray pps_, jint ppsLen,
                                                        jlong timestamp) {
    jbyte *sps = env->GetByteArrayElements(sps_, NULL);
    jbyte *pps = env->GetByteArrayElements(pps_, NULL);
    Rtmp *rtmp = reinterpret_cast<Rtmp *>(cptr);
    int ret = rtmp->sendSpsAndPps((BYTE *) sps, spsLen, (BYTE *) pps, ppsLen, timestamp);

    env->ReleaseByteArrayElements(sps_, sps, 0);
    env->ReleaseByteArrayElements(pps_, pps, 0);
    return ret;
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_ivideo_avcore_rtmplive_RtmpUtils_sendVideoData(JNIEnv *env, jclass clazz, jlong cptr,
                                                        jbyteArray data_, jint len,
                                                        jlong timestamp) {
    jbyte *data = env->GetByteArrayElements(data_, NULL);
    Rtmp *rtmp = reinterpret_cast<Rtmp *> (cptr);
    int ret = rtmp->sendVideoData((BYTE *) data, len, timestamp);

    env->ReleaseByteArrayElements(data_, data, 0);
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_ivideo_avcore_rtmplive_RtmpUtils_sendAacSpec(JNIEnv *env, jclass clazz, jlong cptr,
                                                      jbyteArray data_, jint len) {
    jbyte *data = env->GetByteArrayElements(data_, NULL);

    Rtmp *rtmp = reinterpret_cast<Rtmp *> (cptr);
    int ret = rtmp->sendAacSpec((BYTE *) data, len);

    env->ReleaseByteArrayElements(data_, data, 0);
    return ret;
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_ivideo_avcore_rtmplive_RtmpUtils_sendAacData(JNIEnv *env, jclass clazz, jlong cptr,
                                                      jbyteArray data_, jint len, jlong timestamp) {
    jbyte *data = env->GetByteArrayElements(data_, NULL);

    Rtmp *rtmp = reinterpret_cast<Rtmp *> (cptr);
    int ret = rtmp->sendAacData((BYTE *) data, len, timestamp);

    env->ReleaseByteArrayElements(data_, data, 0);
    return ret;
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_ivideo_avcore_rtmplive_RtmpUtils_stop(JNIEnv *env, jclass clazz, jlong cptr) {
    Rtmp *rtmp = reinterpret_cast<Rtmp *> (cptr);
    delete rtmp;
    return 0;
}
#ifdef __cplusplus
}
#endif